package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.utils.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class NoticeServiceImpl implements INoticeService {
    @Autowired
    private NoticeMapper noticeMapper ;

    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void insert(Notice notice) {
        notice.setCreateUser(UserContext.getEmployee());
        notice.setCreateTime(new Date());
        noticeMapper.insert(notice);
        //查询所有员工id 插入中间表
        Long nid = notice.getId();
        List<Long> ids = employeeMapper.selectAllId();
        for (Long eId : ids) {
            noticeMapper.insertEN(eId,nid);
        }
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice selectById(Long id) {
        Long userId = UserContext.getEmployee().getId();
        noticeMapper.updateRead(userId,id);
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        return notice ;
    }

    @Override
    public List<Notice> selectAll() {
        List<Notice> notices = noticeMapper.selectAll();
        return notices ;
    }

    @Override
    public PageInfo<Notice> query(NoticeQueryObject qo) {
        List<Notice> notices = null ;
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        Employee employee = UserContext.getEmployee();
        if (employee.isAdmin()){
             notices = noticeMapper.queryAll(qo,employee.getId());
        }else {
             notices = noticeMapper.queryRelease(qo,employee.getId());
        }

        return new PageInfo<>(notices);
    }

    //发布
    @Override
    public void issue(Long id,boolean issue) {
        if (issue){
            noticeMapper.issue(id);
        }else {
            noticeMapper.notIssue(id);
        }
    }

}
